<?php

    class socket_adapter {
        private $sock;
        private $client;
        
        public function __construct() {

            set_time_limit (0);
            $address = '0.0.0.0';
            $port = 8982;
            
            if (!($this->sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
                echo " can't create";    
            }
            
            if (!socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1)) { 
                echo " can't set option";        
            }
            
            if (!socket_bind($this->sock, $address, $port)) {
                 echo " can't bind";  
            }
            
        }
       
        public function listen() {

            if (!socket_listen($this->sock)) {
                echo socket_last_error();
                echo " can't listen";
            } 
            
            if (!($this->client = socket_accept($this->sock))) {
                echo " can't accept";
            }
            
        } 

        public function read() {
            if (false ===($bytes = socket_recv($this->client , $input , 10000 , 0))){
                 
            }
            return $input;    
        }

        public function write($output) {   
            $len = strlen($output);   
            $end = false;
            echo "write";
            $a = socket_write($this->client, $len);
            
            $this->read();
            
            while (!$end) {
                echo " write $output";
                if (false === ($number = socket_write($this->client, $output))) {
                    echo "fail";
                }
                echo "number $number";
                echo "len $len";
                if ($number < $len) {
                    $len -= $number;
                    $output = substr($output, $len);
                }  
                else {
                    $end = true;
                } 
                echo "output $output";    
            }
            return $number;      
        }  
        
        public function __destruct() {
            socket_close($this->client);
            socket_close($this->sock);
        }
    }    
?>